/**
 * 分类控制器
 * 处理分类的创建、读取、更新和删除操作
 */

const Category = require('../models/Category');
const Bookmark = require('../models/Bookmark');

/**
 * @desc    获取所有分类
 * @route   GET /api/categories
 * @access  公开
 */
exports.getCategories = async (req, res) => {
  try {
    // 查询参数
    const { parent, includeBookmarkCount } = req.query;
    
    // 构建查询条件
    let query = {};
    
    // 如果指定了parent参数，则查询特定父级下的分类
    if (parent) {
      query.parent = parent === 'null' ? null : parent;
    }
    
    // 查询分类
    let categories = await Category.find(query).sort('order name');
    
    // 如果需要包含书签数量
    if (includeBookmarkCount === 'true') {
      categories = await Category.populate(categories, {
        path: 'bookmarkCount'
      });
    }
    
    res.status(200).json({
      success: true,
      count: categories.length,
      data: categories
    });
  } catch (err) {
    res.status(500).json({
      success: false,
      message: '无法获取分类'
    });
  }
};

/**
 * @desc    获取分类树
 * @route   GET /api/categories/tree
 * @access  公开
 */
exports.getCategoryTree = async (req, res) => {
  try {
    // 获取所有顶级分类
    const rootCategories = await Category.find({ parent: null }).sort('order name');
    
    // 递归获取子分类
    const populateChildren = async (categories) => {
      for (let category of categories) {
        const children = await Category.find({ parent: category._id }).sort('order name');
        
        if (children.length > 0) {
          category._doc.children = children;
          await populateChildren(children);
        } else {
          category._doc.children = [];
        }
      }
    };
    
    await populateChildren(rootCategories);
    
    res.status(200).json({
      success: true,
      data: rootCategories
    });
  } catch (err) {
    res.status(500).json({
      success: false,
      message: '无法获取分类树'
    });
  }
};

/**
 * @desc    获取单个分类
 * @route   GET /api/categories/:id
 * @access  公开
 */
exports.getCategory = async (req, res) => {
  try {
    const category = await Category.findById(req.params.id);
    
    if (!category) {
      return res.status(404).json({
        success: false,
        message: '找不到该分类'
      });
    }
    
    res.status(200).json({
      success: true,
      data: category
    });
  } catch (err) {
    res.status(500).json({
      success: false,
      message: '无法获取分类'
    });
  }
};

/**
 * @desc    创建分类
 * @route   POST /api/categories
 * @access  私有 (仅管理员)
 */
exports.createCategory = async (req, res) => {
  try {
    const category = await Category.create(req.body);
    
    res.status(201).json({
      success: true,
      data: category
    });
  } catch (err) {
    res.status(400).json({
      success: false,
      message: err.message
    });
  }
};

/**
 * @desc    更新分类
 * @route   PUT /api/categories/:id
 * @access  私有 (仅管理员)
 */
exports.updateCategory = async (req, res) => {
  try {
    const category = await Category.findByIdAndUpdate(
      req.params.id,
      req.body,
      {
        new: true, // 返回更新后的文档
        runValidators: true // 运行验证器
      }
    );
    
    if (!category) {
      return res.status(404).json({
        success: false,
        message: '找不到该分类'
      });
    }
    
    res.status(200).json({
      success: true,
      data: category
    });
  } catch (err) {
    res.status(400).json({
      success: false,
      message: err.message
    });
  }
};

/**
 * @desc    删除分类
 * @route   DELETE /api/categories/:id
 * @access  私有 (仅管理员)
 */
exports.deleteCategory = async (req, res) => {
  try {
    const category = await Category.findById(req.params.id);
    
    if (!category) {
      return res.status(404).json({
        success: false,
        message: '找不到该分类'
      });
    }
    
    // 检查是否有书签使用此分类
    const bookmarkCount = await Bookmark.countDocuments({ category: req.params.id });
    
    if (bookmarkCount > 0) {
      return res.status(400).json({
        success: false,
        message: `无法删除此分类，因为有 ${bookmarkCount} 个书签属于此分类`
      });
    }
    
    await category.remove();
    
    res.status(200).json({
      success: true,
      data: {}
    });
  } catch (err) {
    res.status(500).json({
      success: false,
      message: '无法删除分类'
    });
  }
}; 